package com.lm.redis.example;

import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.geo.GeoRadiusParam;

import java.util.List;

public class NearbyPeopleService {
    private Jedis jedis;

    public NearbyPeopleService() {
        // 初始化 Redis 连接
        jedis = new Jedis("localhost", 6379);
    }

    // 添加用户位置信息
    public void addUserLocation(String userId, double longitude, double latitude) {
        jedis.geoadd("users", longitude, latitude, userId);
    }

    // 查询指定用户附近的其他用户
    public List<GeoRadiusResponse> findNearbyUsers(String userId, double radiusInKm) {
        // 获取用户的经纬度
        List<GeoCoordinate> userPosition = jedis.geopos("users", userId);
        if (userPosition.isEmpty()) {
            throw new IllegalArgumentException("User not found: " + userId);
        }

        double longitude = ((List<Double>) userPosition.get(0)).get(0);
        double latitude = ((List<Double>) userPosition.get(0)).get(1);

        // 查询附近的用户
        return jedis.georadius("users", longitude, latitude, radiusInKm, GeoUnit.KM,
                GeoRadiusParam.geoRadiusParam().withDist().sortAscending());
    }

    public static void main(String[] args) {
        NearbyPeopleService service = new NearbyPeopleService();

        // 添加几位用户的位置
        service.addUserLocation("user1", 116.403963, 39.915119);  // 北京
        service.addUserLocation("user2", 121.473701, 31.230416);  // 上海
        service.addUserLocation("user3", 114.305393, 30.592850);  // 武汉

        // 查询 user1 附近 1000 公里内的用户
        List<GeoRadiusResponse> nearbyUsers = service.findNearbyUsers("user1", 1000);
        nearbyUsers.forEach(user ->
                System.out.println("User: " + user.getMemberByString() + ", Distance: " + user.getDistance()));
    }
}
